import axios from 'axios';
import config from '~/config';
import { Toast } from 'mint-ui';

axios.defaults.baseURL = config.BASE_URL
axios.defaults.timeout = config.TIMEOUT
axios.defaults.headers = config.HEADERS

// 请求拦截器处理数据

axios.interceptors.request.use(request => {
    if (!config.IS_RELEASE) {
        console.log(
            `${new Date().toLocaleString()}【 M=${request.url} 】P=`,
            request.params || request.data,
        );
    }
    return request;
}, error => {
    return Promise.reject(error)
})

export default async (options = { method: 'GET' }) => {
    let isData = true
    if (options.method.toUpperCase() !== 'POST' && options.method.toUpperCase() !== 'PUT' && options.method.toUpperCase() !== 'PATCH') {
        isData = false
    }
    const res = await axios({
        method: options.method,
        url: options.url,
        data: isData ? options.data : null,
        params: !isData ? options.data : null,
    })
    if (res.status >= 200 && res.status < 300) {
        if (!config.IS_RELEASE) {
            console.log(`${new Date().toLocaleString()}【接口响应：】`, res.data)
        }

        if (typeof window !== 'undefined' && res.data.code !== 0) {
            Toast(res.data.msg)
        }
        return res.data
    } else {
        if (typeof window !== "undefined" && res.data.code !== 0) {
            Toast('请求错误');
        }
    }

}